<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>PEP 278 -- Universal Newline Support</title>
  <meta name="keywords" content="None" />
  <meta name="description" content="None" />
  <link rel="alternate" type="application/rss+xml" title="Community Events"
        href="http://www.python.org/channews.rdf" />
  <link rel="alternate" type="application/rss+xml" title="Python Recipes"
        href="http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss" />
  <link rel="alternate" type="application/rss+xml" title="Usergroup News"
        href="http://python-groups.blogspot.com/feeds/posts/default" />
  <link rel="alternate" type="application/rss+xml" title="Python Screencasts"
        href="http://www.showmedo.com/latestVideoFeed/rss2.0?tag=python" />
  <link rel="alternate" type="application/rss+xml" title="Python Podcasts"
        href="http://www.awaretek.com/python/index.xml" />
  <link rel="alternate" type="application/rss+xml" title="Foundation News"
        href="http://pyfound.blogspot.com/feeds/posts/default" />
  <link rel="alternate" type="application/rss+xml" title="Python Enhancement Proposals"
        href="http://www.python.org/dev/peps/peps.rss" />
  <link rel="alternate" type="application/rss+xml" title="Python Job Opportunities"
        href="http://www.python.org/community/jobs/jobs.rss" />
  <link rel="alternate" type="application/rss+xml" title="Reddit Feed of Python What's New Online"
        href="http://www.reddit.com/r/Python/.rss" />

  <link rel="stylesheet" type="text/css" media="screen" id="screen-switcher-stylesheet"
        href="/styles/screen-switcher-default.css" />
  <link rel="stylesheet" type="text/css" media="sc&#82;een"
        href="/styles/netscape4.css" />
  <link rel="stylesheet" type="text/css" media="print"
        href="/styles/print.css" />
  <link rel="alternate stylesheet" type="text/css" media="screen"
        href="/styles/largestyles.css" title="large text" />
  <link rel="alternate stylesheet" type="text/css" media="screen"
        href="/styles/defaultfonts.css" title="default fonts" />

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search under the www.python.org Domain"
        href="/search-pysite.xml"/>

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search within the Python Wiki"
        href="/search-pywiki.xml"/>

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search within Python Books at Google Book Search"
        href="/search-pybooks.xml"/>

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search within the Python Documentation"
        href="/search-pydocs.xml"/>

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search for a Module in the Standard Library"
        href="/search-pymodules.xml"/>

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search for Packages inside the Cheeseshop (PyPI)"
        href="/search-pycheese.xml"/>

  <link rel="search" type="application/opensearchdescription+xml"
        title="Search Archives of the Main Python Mailing List"
        href="/search-pythonlist.xml"/>

  <script type="text/javascript" src="/js/iotbs2-key-directors-load.js"></script>
  <script type="text/javascript" src="/js/iotbs2-directors.js"></script>
  <script type="text/javascript" src="/js/iotbs2-core.js"></script>

</head>


<body>
  <!-- Logo -->
  <h1 id="logoheader">
    <a href="/" id="logolink" accesskey="1"><img id="logo" src="/images/python-logo.gif" alt="homepage" border="0" /></a>
  </h1>
  <!-- Skip to Navigation -->
  <div class="skiptonav"><a href="#left-hand-navigation" accesskey="2"><img src="/images/trans.gif" id="skiptonav" alt="skip to navigation" border="0" /></a></div>
  <div class="skiptonav"><a href="#content-body" accesskey="3"><img src="/images/trans.gif" id="skiptocontent" alt="skip to content" border="0" /></a></div>
  <!-- Utility Menu -->
  <div id="utility-menu">
    <!-- Search Box -->
    <div id="searchbox">
      <form method="get" action="http://google.com/search" id="searchform" name="searchform">
        <div id="search">
          <input type="hidden" id="domains" name="domains" value="www.python.org" />
          <input type="hidden" id="sitesearch" name="sitesearch" value="www.python.org" />
          <input type="hidden" id="sourceid" name="sourceid" value="google-search" />
          <input type="text" class="input-text" name="q" id="q" />
          <input type="submit" value="search" class="input-button" name="submit" id="submit" />
          <a href="/search" class="reference">Advanced Search</a>
        </div>
      </form>
    </div>
    <div id="screen-switcher"></div>
  </div>

  <div id="left-hand-navigation">
    <!-- Main Menu -->
    <div id="menu">
      <ul class="level-one">
            <li>
          <a href="/about/" title="About The Python Language">About</a>
        </li>
            <li>
          <a href="/news/" title="Major Happenings Within the Python Community">News</a>
        </li>
            <li>
          <a href="/doc/" title="Tutorials, Library Reference, C API">Documentation</a>
        </li>
            <li>
          <a href="/download/" title="Start Running Python Under Windows, Mac, Linux and Others">Download</a>
        </li>
            <li>
          <a href="/community/" title="Mailing Lists, Jobs, Conferences, SIGs, Online Chats">Community</a>
        </li>
            <li>
          <a href="/psf/" title="Python Software Foundation">Foundation</a>
        </li>
            <li class="selected">
          <a href="/dev/" title="Development of the Python language and website" class="selected">Core Development</a>
	    <ul class="level-two">
		<li>
	      <a href="/dev/tools/">Tools</a>
              </li>
		<li>
	      <a href="/dev/setup/">Getting Set Up</a>
              </li>
		<li>
	      <a href="/dev/intro/">Intro to Development</a>
              </li>
		<li>
	      <a href="/dev/contributing/">Suggested Tasks</a>
              </li>
		<li>
	      <a href="http://svn.python.org/view/">Browse Subversion</a>
              </li>
		<li>
	      <a href="http://svn.python.org/snapshots/">Daily Snapshots</a>
              </li>
		<li>
	      <a href="http://bugs.python.org">Issue Tracker</a>
              </li>
		<li>
	      <a href="/dev/patches/">Patch Submission</a>
              </li>
		<li class="selected">
	      <a href="/dev/peps/" class="selected">PEP Index</a>
              </li>
		<li>
	      <a href="/dev/workflow/">Issue Workflow</a>
              </li>
		<li>
	      <a href="/dev/faq/">FAQ</a>
              </li>
		<li>
	      <a href="/dev/buildbot/">Buildbot</a>
              </li>
		<li>
	      <a href="/dev/doc/">Documenting Python</a>
              </li>
		<li>
	      <a href="/dev/pydotorg/">Python.org</a>
              </li>
	    </ul>
        </li>
      </ul>
    </div>

    <!-- Quick Links -->
    <h4><a style="margin-top:1.5em" href="http://wiki.python.org/moin/">Python Wiki</a></h4>
    <h4><a style="margin-top:1.5em" href="http://wiki.python.org/moin/Python2orPython3">Python 2 or 3?</a></h4>
    <h4><a style="margin-top:1.5em" href="/about/website">Help Maintain Website</a></h4> 
    <h4><a style="color:#D58228; margin-top:1.5em" href="/psf/donations/">Help Fund Python</a></h4>
    <div style="align:center; padding-top: 0.5em; padding-left: 1em">
      <a href="/psf/donations/"><img width="116" height="42" src="/images/donate.png" alt="" title="" /></a>
    </div>
    <div style="align:center; padding-top: 0.5em; padding-left: 2.5em">
            <a href="http://wiki.python.org/moin/Languages"><img
	      style="align:center"
              width="94" height="46"
	      src="/images/worldmap.jpg" alt="[Python resources in languages other than English]" /></a>
    </div>
    <div style="align:center; padding-top: 0.0em; padding-left: 0em">
       <h4><a href="http://wiki.python.org/moin/Languages">Non-English Resources</a></h4>
    </div>
    <div style="align:center; padding-top: 0.0em; padding-left: 0em">
        <iframe src="https://www.google.com/calendar/embed?title=Release%20Schedule&amp;showNav=0&amp;showDate=0&amp;showPrint=0&amp;showTabs=0&amp;showCalendars=0&amp;showTz=0&amp;mode=AGENDA&amp;height=300&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=b6v58qvojllt0i6ql654r1vh00%40group.calendar.google.com&amp;color=%23B1365F&amp;" style=" border-width:0 " width="180" height="300" frameborder="0" scrolling="no">
            <a href="http://www.google.com/calendar/ical/b6v58qvojllt0i6ql654r1vh00%40group.calendar.google.com/public/basic.ics">
                Python Release Schedule iCal Calendar
            </a>
        </iframe>
    </div>
  </div>

  <div id="content-body">
    <div id="body-main">
      <div id="content">
        
          <div id="breadcrumb">
               <a href="/dev/">Core Development</a>
               <span class="breadcrumb-separator">&gt;</span>
               <a href="/dev/peps/">PEP Index</a>
               <span class="breadcrumb-separator">&gt;</span>
            
            PEP 278 -- Universal Newline Support
          </div>



        <!--
This HTML is auto-generated.  DO NOT EDIT THIS FILE!  If you are writing a new
PEP, see http://www.python.org/dev/peps/pep-0001 for instructions and links
to templates.  DO NOT USE THIS HTML FILE AS YOUR TEMPLATE!
-->
<div class="header">
<table border="0" class="rfc2822">
  <tr><th class="field-name">PEP:&nbsp;</th><td>278</td></tr>
  <tr><th class="field-name">Title:&nbsp;</th><td>Universal Newline Support</td></tr>
  <tr><th class="field-name">Version:&nbsp;</th><td>83556</td></tr>
  <tr><th class="field-name">Last-Modified:&nbsp;</th><td><a href="http://svn.python.org/view/*checkout*/peps/trunk/pep-0278.txt"> 2010-08-02 21:50:16 +0200 (Mon, 02 Aug 2010)</a> </td></tr>
  <tr><th class="field-name">Author:&nbsp;</th><td>Jack Jansen &lt;jack&#32;&#97;t&#32;cwi.nl&gt;</td></tr>
  <tr><th class="field-name">Status:&nbsp;</th><td>Final</td></tr>
  <tr><th class="field-name">Type:&nbsp;</th><td>Standards Track</td></tr>
  <tr><th class="field-name">Created:&nbsp;</th><td>14-Jan-2002</td></tr>
  <tr><th class="field-name">Python-Version:&nbsp;</th><td>2.3</td></tr>
  <tr><th class="field-name">Post-History:&nbsp;</th><td></td></tr>
</table>
</div>
<h3>Abstract</h3>
<pre>
    This PEP discusses a way in which Python can support I/O on files
    which have a newline format that is not the native format on the
    platform, so that Python on each platform can read and import
    files with CR (Macintosh), LF (Unix) or CR LF (Windows) line
    endings.

    It is more and more common to come across files that have an end
    of line that does not match the standard on the current platform:
    files downloaded over the net, remotely mounted filesystems on a
    different platform, Mac OS X with its double standard of Mac and
    Unix line endings, etc.
    
    Many tools such as editors and compilers already handle this
    gracefully, it would be good if Python did so too.


</pre>
<h3>Specification</h3>
<pre>
    Universal newline support is enabled by default,
    but can be disabled during the configure of Python.
    
    In a Python with universal newline support the feature is
    automatically enabled for all import statements and execfile()
    calls. There is no special support for eval() or exec.
    
    In a Python with universal newline support open() the mode
    parameter can also be "U", meaning "open for input as a text file
    with universal newline interpretation".  Mode "rU" is also allowed,
    for symmetry with "rb". Mode "U" cannot be
    combined with other mode flags such as "+". Any line ending in the
    input file will be seen as a '\n' in Python, so little other code has
    to change to handle universal newlines.
    
    Conversion of newlines happens in all calls that read data: read(),
    readline(), readlines(), etc.
    
    There is no special support for output to file with a different
    newline convention, and so mode "wU" is also illegal.
    
    A file object that has been opened in universal newline mode gets
    a new attribute "newlines" which reflects the newline convention
    used in the file.  The value for this attribute is one of None (no
    newline read yet), "\r", "\n", "\r\n" or a tuple containing all the
    newline types seen.

    
</pre>
<h3>Rationale</h3>
<pre>
    Universal newline support is implemented in C, not in Python.
    This is done because we want files with a foreign newline
    convention to be import-able, so a Python Lib directory can be
    shared over a remote file system connection, or between MacPython
    and Unix-Python on Mac OS X.  For this to be feasible the
    universal newline convention needs to have a reasonably small
    impact on performance, which means a Python implementation is not
    an option as it would bog down all imports. And because of files
    with multiple newline conventions, which Visual C++ and other
    Windows tools will happily produce, doing a quick check for the
    newlines used in a file (handing off the import to C code if a
    platform-local newline is seen) will not work.  Finally, a C
    implementation also allows tracebacks and such (which open the
    Python source module) to be handled easily.
    
    There is no output implementation of universal newlines, Python
    programs are expected to handle this by themselves or write files
    with platform-local convention otherwise.  The reason for this is
    that input is the difficult case, outputting different newlines to
    a file is already easy enough in Python.
    
    Also, an output implementation would be much more difficult than an
    input implementation, surprisingly: a lot of output is done through
    PyXXX_Print() methods, and at this point the file object is not
    available anymore, only a FILE *. So, an output implementation would
    need to somehow go from the FILE* to the file object, because that
    is where the current newline delimiter is stored.

    The input implementation has no such problem: there are no cases in
    the Python source tree where files are partially read from C,
    partially from Python, and such cases are expected to be rare in
    extension modules. If such cases exist the only problem is that the
    newlines attribute of the file object is not updated during the
    fread() or fgets() calls that are done direct from C.

    A partial output implementation, where strings passed to fp.write()
    would be converted to use fp.newlines as their line terminator but
    all other output would not is far too surprising, in my view.

    Because there is no output support for universal newlines there is
    also no support for a mode "rU+": the surprise factor of the
    previous paragraph would hold to an even stronger degree.

    There is no support for universal newlines in strings passed to
    eval() or exec. It is envisioned that such strings always have the
    standard \n line feed, if the strings come from a file that file can
    be read with universal newlines.

    I think there are no special issues with unicode. utf-16 shouldn't
    pose any new problems, as such files need to be opened in binary
    mode anyway. Interaction with utf-8 is fine too: values 0x0a and 0x0d
    cannot occur as part of a multibyte sequence.

    Universal newline files should work fine with iterators and
    xreadlines() as these eventually call the normal file
    readline/readlines methods.

    
    While universal newlines are automatically enabled for import they
    are not for opening, where you have to specifically say open(...,
    "U"). This is open to debate, but here are a few reasons for this
    design:

    - Compatibility.  Programs which already do their own
      interpretation of \r\n in text files would break. Examples of such
      programs would be editors which warn you when you open a file with
      a different newline convention. If universal newlines was made the
      default such an editor would silently convert your line endings to
      the local convention on save. Programs which open binary files as
      text files on Unix would also break (but it could be argued they
      deserve it :-).
      
    - Interface clarity.  Universal newlines are only supported for
      input files, not for input/output files, as the semantics would
      become muddy.  Would you write Mac newlines if all reads so far
      had encountered Mac newlines?  But what if you then later read a
      Unix newline?
    
    The newlines attribute is included so that programs that really
    care about the newline convention, such as text editors, can
    examine what was in a file.  They can then save (a copy of) the
    file with the same newline convention (or, in case of a file with
    mixed newlines, ask the user what to do, or output in platform
    convention).
    
    Feedback is explicitly solicited on one item in the reference
    implementation: whether or not the universal newlines routines
    should grab the global interpreter lock.  Currently they do not,
    but this could be considered living dangerously, as they may
    modify fields in a FileObject.  But as these routines are
    replacements for fgets() and fread() as well it may be difficult
    to decide whether or not the lock is held when the routine is
    called.  Moreover, the only danger is that if two threads read the
    same FileObject at the same time an extraneous newline may be seen
    or the "newlines" attribute may inadvertently be set to mixed.  I
    would argue that if you read the same FileObject in two threads
    simultaneously you are asking for trouble anyway.
    
    Note that no globally accessible pointers are manipulated in the
    fgets() or fread() replacement routines, just some integer-valued
    flags, so the chances of core dumps are zero (he said:-).
    
    Universal newline support can be disabled during configure because it does
    have a small performance penalty, and moreover the implementation has
    not been tested on all concievable platforms yet. It might also be silly
    on some platforms (WinCE or Palm devices, for instance). If universal
    newline support is not enabled then file objects do not have the "newlines"
    attribute, so testing whether the current Python has it can be done with a
    simple

        if hasattr(open, 'newlines'):
            print 'We have universal newline support'

    Note that this test uses the open() function rather than the file
    type so that it won't fail for versions of Python where the file
    type was not available (the file type was added to the built-in
    namespace in the same release as the universal newline feature was
    added).

    Additionally, note that this test fails again on Python versions
    &gt;= 2.5, when open() was made a function again and is not synonymous
    with the file type anymore.

    
</pre>
<h3>Reference Implementation</h3>
<pre>
    A reference implementation is available in SourceForge patch
    #476814: <a href="http://www.python.org/sf/476814">http://www.python.org/sf/476814</a>


</pre>
<h3>References</h3>
<pre>
    None.


</pre>
<h3>Copyright</h3>
<pre>
    This document has been placed in the public domain.


</pre>


      </div>

      
      <div id="footer">
	<div id="credits">
 	  <a href="/about/website">Website maintained by the Python community</a><br/>
	  <a href="http://www.xs4all.com/" title="Web and email hosting provided by xs4all, Netherlands">hosting by xs4all</a> /
	  <a href="http://www.timparkin.co.uk/" title="Design by Tim Parkin, Yorkshire man, photographer and developer">design by Tim Parkin</a>
	</div>
	Copyright &copy; 1990-2010, <a href='/psf/'>Python Software Foundation</a><br/>
	<a href="/about/legal">Legal Statements</a>
      </div>


    </div>
  </div>
</body>
</html>






